<template>
  <div class="supplier-wrap">
    <ListTab v-if="!showMobilePage" show-header is-table />
    <div :class="{'mobile-table mobile-pt mobile-min-height':showMobilePage}" class="table-list min-fill-page">
      <div v-if="!showMobilePage" class="table-box-title">
        <FilterInput
          ref="FilterToolRef"
          v-model="filterForm"
          :filter-list="filterList"
          show-search-btn
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus"/>
        <div class="btn-right" style="align-items: center;display: flex;">
          <create-button v-if="hasRouteAuth('mengli:supplier:create')" :add-name="'新增'" :create-link-name="'mengliCreateSupplier'" class="btn-right-item"/>
          <MoreOpeator
            ref="moreOpeatorRef"
            :list="[
              { label: '导入', importApi: 'admin/mengli/suppliers/import', callback: fetchData, type: 'import', auth: hasRouteAuth('mengli:supplier:import') },
              { label: '导出', exportApi:'admin/mengli/suppliers/export', type: 'export', exportName: '萌力供应商', isBeforeExport:true,
                auth: hasRouteAuth('mengli:supplier:export'), beforeExport: exportBeforeExport, refName:'mengliExportRef' },
              { label: '导入模板下载', exportApi: 'admin/mengli/template/export', exportName: '萌力供应商模板', type: 'export' },
            ]"
            style="margin-left:16px;"
          />
        </div>
      </div>
      <div v-loading="listLoading" style="min-height: 300px;">
        <u-table
          v-if="list.items.length > 0"
          ref="tableRef"
          :data="list.items"
          :height="setTableHeight"
          :row-height="rowHeight()"
          :border="true"
          :row-class-name="tableRowClassName"
          beautify-table
          header-drag-style
          use-virtual
          class="fb-table"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell"
          fit
          hightlight-current-row
          @select="selectTable"
          @select-all="selectTable"
          @sort-change="sortMethod">
          <u-table-column
            :fixed="selectFixed"
            align="center"
            type="selection"
            width="50"/>
          <u-table-column align="left" label="供应商名称" min-width="145">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.supplier" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.supplier }}</div>
                <div class="remark-text ellipsisOne" style="cursor:pointer;color:#406eff;" @click="mengliDetail(scope)">{{ scope.row.supplier }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="供应商类型" min-width="145" prop="supplierType">
            <template slot-scope="scope">
              {{ scope.row.supplierType | supplierStatus }}
            </template>
          </u-table-column>
          <u-table-column align="left" label="标签" width="150">
            <template slot-scope="scope">
              <TagSelect v-model="scope.row.tag" mode="list" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="可抵扣税率" min-width="100">
            <template slot-scope="scope">
              <div v-if="scope.row.deductionRate || scope.row.deductionRate === 0">{{ scope.row.deductionRate }}%</div>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="总订单数" width="100" prop="orderNum" sortable="custom">
            <template slot-scope="scope">
              <div v-if="scope.row.orderNum || scope.row.orderNum === 0">{{ scope.row.orderNum }}</div>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="待结订单" min-width="130" prop="notSupplierNum" sortable="custom">
            <template slot-scope="scope">
              <div v-if="scope.row.notSupplierNum || scope.row.notSupplierNum === 0">{{ scope.row.notSupplierNum }}</div>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="总成本数" width="100" prop="costNum" sortable="custom">
            <template slot-scope="scope">
              <div v-if="scope.row.costNum || scope.row.costNum === 0">{{ scope.row.costNum }}</div>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="待结订单成本(元)" width="160" prop="notOrderCostNum" sortable="custom">
            <template slot-scope="scope">
              <div v-if="scope.row.notOrderCostNum || scope.row.notOrderCostNum === 0">{{ scope.row.notOrderCostNum }}</div>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="待结成本(元)" min-width="150" prop="notCostNum" sortable="custom">
            <template slot="header" slot-scope="scope">
              <div class="table-header">
                <div class="flex">
                  <span class="label">{{ scope.column.label }}</span>
                  <tipIcon content="仅统计未关联订单的成本"/>
                </div>
              </div>
            </template>
            <template slot-scope="scope">
              <div v-if="scope.row.notCostNum || scope.row.notCostNum === 0">{{ scope.row.notCostNum }}</div>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <!-- <u-table-column align="left" label="关联订单" min-width="145" prop="overdueOrder">
            <template slot-scope="scope">
              {{ scope.row.relatedOrder | moneyFilter }}
            </template>
          </u-table-column> -->
          <u-table-column align="left" label="协作人" min-width="80">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.associate" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建人" min-width="80">
            <template slot-scope="scope">
              {{ scope.row.creator || '--' }}
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建时间" min-width="165" prop="createTime" sortable="custom">
            <template slot-scope="scope">
              {{ scope.row.createTime | standardFormat('YYYY/MM/DD HH:mm') }}
            </template>
          </u-table-column>
          <u-table-column align="left" label="备注" min-width="140">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.remark" />
            </template>
          </u-table-column>
          <u-table-column :width="operateWidth" :fixed="operateFix" align="left" label="操作">
            <template slot-scope="scope">
              <div v-if="!showMobilePage" class="button-container">
                <el-dropdown
                  v-if="(hasRouteAuth('medium:supplierAudit:launch'))"
                  trigger="click">
                  <div class="button-text">结算</div>
                  <el-dropdown-menu slot="dropdown" style="padding:0;">
                    <el-dropdown-item style="width:130px;padding:0;text-align:center;" @click.native="settlement(scope.row, 0)">
                      <div>订单成本付款结算</div>
                    </el-dropdown-item>
                    <el-dropdown-item style="width:130px;padding:0;text-align:center;" @click.native="settlement(scope.row, 1)">
                      <div>其他付款结算(非订单)</div>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <el-dropdown trigger="click">
                  <div :class="{'bl': (hasRouteAuth('medium:supplierAudit:launch'))}" class="button-text">更多<i class="el-icon-arrow-down"/></div>
                  <el-dropdown-menu slot="dropdown" style="margin-top:-10px;margin-right:15px;padding: 0;">
                    <el-dropdown-item style="width:80px;text-align: center" @click.native="mengliDetail(scope)">
                      <div>查看</div>
                    </el-dropdown-item>
                    <el-dropdown-item :disabled="!hasRouteAuth('mengli:supplier:edit')" style="width:80px;text-align: center" @click.native="toEdit(scope)">
                      <div>编辑</div>
                    </el-dropdown-item>
                    <el-dropdown-item :disabled="!hasRouteAuth('mengli:supplier:delete')" style="width:80px;text-align: center" @click.native="todelete(scope.row.id)">
                      <div>删除</div>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
              <tableOperateBtn v-else :is-hide-on-click="false">
                <el-dropdown-item v-if="hasRouteAuth('medium:supplierAudit:launch')">
                  <el-dropdown :hide-on-click="false">
                    <div style="font-size: 14px;">结算</div>
                    <el-dropdown-menu slot="dropdown" style="padding:0;">
                      <el-dropdown-item style="width:130px;padding:0;text-align:center;" @click.native="settlement(scope, 0)">
                        <div>订单成本付款结算</div>
                      </el-dropdown-item>
                      <el-dropdown-item style="width:130px;padding:0;text-align:center;" @click.native="settlement(scope, 1)">
                        <div>其他付款结算(非订单)</div>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </el-dropdown-item>
                <el-dropdown-item style="width:80px;text-align: center" @click.native="mengliDetail(scope)">
                  <div>查看</div>
                </el-dropdown-item>
                <el-dropdown-item :disabled="!hasRouteAuth('mengli:supplier:edit')" style="width:80px;text-align: center" @click.native="toEdit(scope)">
                  <div>编辑</div>
                </el-dropdown-item>
                <el-dropdown-item :disabled="!hasRouteAuth('mengli:supplier:delete')" style="width:80px;text-align: center" @click.native="todelete(scope.row.id)">
                  <div>删除</div>
                </el-dropdown-item>
              </tableOperateBtn>
            </template>
          </u-table-column>
        </u-table>
        <empty-placeholder v-else-if="!list.isInit" style="margin-bottom: 24px" />
      </div>
      <el-row v-if="showMobilePage" type="flex" justify="left">
        <el-pagination
          v-show="list.total > 0"
          :current-page.sync="page"
          :page-size="perPage"
          :total="list.total"
          :small="true"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="pageLayout"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
      <fixed-pagination v-if="list.total > 0 && !showMobilePage || showMobilePage">
        <template v-if="showMobilePage">
          <FilterInput
            ref="FilterToolRef"
            v-model="filterForm"
            :filter-list="filterList"
            show-search-btn
            show-mobile-icon
            @handelClick="queryClick"
            @queryEmpty="queryEmpty"
            @filterTagStatus="filterTagStatus"/>
          <MoreOpeator
            ref="moreOpeatorRef"
            :list="[
              { label: '导入', importApi: 'admin/mengli/suppliers/import', callback: fetchData, type: 'import', auth: hasRouteAuth('mengli:supplier:import') },
              { label: '导出', exportApi:'admin/mengli/suppliers/export', type: 'export', exportName: '萌力供应商', isBeforeExport:true,
                auth: hasRouteAuth('mengli:supplier:export'), beforeExport: exportBeforeExport, refName:'mengliExportRef' },
              { label: '导入模板下载', exportApi: 'admin/mengli/template/export', exportName: '萌力供应商模板', type: 'export' },
            ]"
            show-mobile-icon
            style="margin-left:16px;"
          />
          <createBtn v-if="hasRouteAuth('mengli:supplier:create')" mobile-table show-mobile-icon @click.native="toCreate"/>
        </template>
        <template v-else>
          <!-- <div v-if="timeDiff >= 60">
          <el-tooltip :open-delay="800" placement="top">
            <div slot="content" style="max-width: 200px;">统计数据预计一分钟内完成更新，刷新页面后可查看最新数据</div>
            <div class="update-time"><img :src="cacheTimeIcon" alt=""> 列表统计数据更新时间：{{ cacheTime | format('YYYY/MM/DD HH:mm') }}</div>
          </el-tooltip>
        </div> -->
          <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
          <div style="flex:1;"/>
          <el-pagination
            v-show="list.total > 0"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </template>
      </fixed-pagination>
    </div>
  </div>
</template>
<script>
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import createButton from '@/components/CreateButton';
import Title from '@/components/Title';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import ListTab from '@/components/ListTab';
import TagSelect from '@/components/Common/tagSelect';
import createBtn from '@/components/Common/baseComponent/createBtn';
import { standardFormat } from '@/filters/date';
import { moneyFilter } from '@/filters/number';
import { getSuppliers, deleteSupplier } from '@/api/mengli';
import { getTagAll } from '@/api/config';
import { hasRouteAuth } from '@/utils/permission';
import { TAG_MODULES } from '@/utils/const';
import { paramsAryToStr } from '@/utils/paramsFormat';
import TableAdaptive from '@/mixins/tableAdaptive';
import tableSelections from '@/mixins/tableSelections';
import mobileTable from '@/mixins/mobileTable';
import setting from '@/assets/setting.png';

export default {
  name: 'SupplierList',
  filters: {
    standardFormat,
    moneyFilter,
    supplierStatus(type) {
      const obj = {
        '0': '公司',
        '1': '个人'
      };
      return obj[String(type)] || '--';
    }
  },
  components: {
    createButton,
    Title,
    EmptyPlaceholder, ListTab,
    MoreOpeator,
    createBtn,
    TagSelect
  },
  mixins: [TableAdaptive, tableSelections, mobileTable],
  data() {
    return {
      TAG_MODULES,
      setting,
      filterForm: {
        keyword: '',
        supplierType: null
      },
      page: 1,
      perPage: 20,
      listLoading: true,
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInit: true
      },
      supplierTypeOption: [
        { value: -1, label: '全部' },
        { value: 1, label: '个人' },
        { value: 0, label: '公司' }
      ],
      sortName: '',
      sortType: '',
      cacheTime: '',
      tagTreeList: [],
      arrayKeyArr: ['tag'],
      tableRefName: 'tableRef', // 表格的ref名称
      isUmyTable: true,
      idKey: 'id' // 唯一表示字段
    };
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'mengliEditSupplier') {
      to.meta.isChange = true;
    } else {
      to.meta.isChange = false;
    }
    next();
  },
  computed: {
    tableOutsideHeight() {
      return this.showMobilePage ? 152 : 190;
    },
    timeDiff() {
      const updateTime = this.cacheTime;
      if (!updateTime) return 0;
      let time = Date.parse(new Date());
      if (updateTime.toString().length === 10) {
        time = Math.round(time / 1000);
      }
      return time - Number(updateTime);
    },
    filterList() {
      return [
        { keyword: 'keyword', name: '供应商名称', type: 'input' },
        { keyword: 'associate', name: '协作人', type: 'input' },
        { keyword: 'supplierType', name: '供应商类型', type: 'select', options: this.supplierTypeOption },
        { keyword: 'tag', name: '标签', valueName: 'id', labelName: 'name',
          childrenVal: 'item', type: 'cascaderSelect', checkStrictly: false, options: this.tagTreeList,
          multiple: true, filterable: true, collapseTags: true
        }
      ];
    }
  },
  activated() {
    if (!this.$route.meta.isChange && !this.$route.query.keyword) {
      this.queryEmpty();
    } else {
      if (this.$route.query.keyword) {
        this.filterForm = this.$route.query;
      }
      this.fetchData(this.list && this.list.items && this.list.items.length === 0);
    }
    this.queryTagTreeList();
  },
  methods: {
    hasRouteAuth,
    // 跳转萌力详情
    mengliDetail(scope) {
      this.$router.push({
        name: 'mengliSupplierDetail',
        params: { id: scope.row.id }
      });
    },
    settlement(item, type) {
      const query = { id: item.id, from: 'mengliSupplier' };
      if (type === 1) query.isNotOrder = 1;
      this.$router.push({
        name: 'supplierCreate', // supplierCreate\supplierDetail
        query
      });
    },
    toCreate() {
      this.$router.push({
        name: 'mengliCreateSupplier'
      });
    },
    queryClick() {
      this.fetchData(true);
    },
    formatParams() {
      const params = JSON.parse(JSON.stringify(this.filterForm));
      params.sortName = this.sortName;
      params.sortType = this.sortType;
      paramsAryToStr(this.arrayKeyArr, params);
      return params;
    },
    fetchData(reset = false) {
      if (reset) this.page = 1;
      this.listLoading = true;
      const params = this.formatParams();
      getSuppliers(this.page, this.perPage, params).then(({ data }) => {
        if (data && data.items && data.items[0] && data.items[0].cacheTime) {
          this.cacheTime = data.items[0].cacheTime;
        }
        this.list = data;
        this.list.associate = this.list.associate ? this.list.associate.map(item => {
          return item.name;
        }).join(',') : '';
        if (this.setSelectRow) this.setSelectRow(data.items);
        this.list.isInit = false;
        this.listLoading = false;
      }, result => {
        this.listLoading = false;
      }).catch(e => {
        console.error(e);
      });
    },
    queryEmpty() {
      this.filterForm = {};
      this.queryClick();
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true);
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.fetchData();
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    queryTagTreeList() {
      const params = { type: this.TAG_MODULES.MENGLI_SUPPLIER };
      getTagAll(params).then(res => {
        this.tagTreeList = (res && res.data) || [];
        this.tagTreeList.forEach(item => {
          if (!item.item) item.disabled = true;
        });
      }).catch(e => {
        console.log(e);
      });
    },
    sortMethod(a) {
      if (a.order) {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      } else {
        this.sortName = '';
        this.sortType = '';
      }
      this.fetchData();
    },
    toEdit(scope) {
      this.$router.push({
        name: 'mengliEditSupplier',
        params: { id: scope.row.id }
      });
    },
    todelete(id) {
      this.$confirm('是否确定删除', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true,
        type: 'warning',
        customClass: ' del-message del-message-cancel',
        iconClass: 'del-icon'
      }).then(() => {
        deleteSupplier(id).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            if (this.page > 1 && this.perPage * (this.page - 1) + 1 === this.list.total) {
              this.page--;
            }
            this.resetItemSelected(id);
            this.fetchData();
          } else {
            this.$message.warning(res.message);
          }
        });
      }).catch(() => {});
    },
    exportBeforeExport() {
      const params = this.formatParams();
      if (this.multipleSelectionAll.length) {
        params.ids = this.multipleSelectionAll.map(el => el.id).join(',');
      }
      if (this.$refs.moreOpeatorRef) {
        this.$refs.moreOpeatorRef.btnExport(params, 'mengliExportRef');
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.supplier-wrap {
  .table-list {
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding: 20px 20px 55px 20px;
    .table-box-title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 16px;
      & ::v-deep {
        .el-form-item {
          margin-bottom: 0;
        }
      }
    }
  }
  &::v-deep {
    .supplier-loading-text {
      .el-loading-text {
        position: relative;
        &::after {
          content: '首次加载较慢，请耐心等待';
          display: block;
        }
      }
    }
  }
}
.table-header {
  display: inline-block;
  .flex {
    display: flex;
    align-items: center;
  }
}
.button-container {
  display: flex;
}
</style>
